/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-17 9:40:42
 ******************************************************************************/
package cn.cmcc.online.smsapi.sdk.iccid;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import android.telephony.TelephonyManager;
import cn.cmcc.online.smsapi.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.cmcc.online.smsapi.sdk.Iservice.XyCallBack;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.entity.CenterNumLocationInfo;
import cn.cmcc.online.smsapi.sdk.db.entity.IccidInfo;
import cn.cmcc.online.smsapi.sdk.db.entity.IccidInfoManager;
import cn.cmcc.online.smsapi.sdk.db.entity.SysParamEntityManager;
import cn.cmcc.online.smsapi.sdk.db.entity.pubinfo.CNumLocationInfoManager;
import cn.cmcc.online.smsapi.sdk.dex.DexUtil;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.net.NetUtil;
import cn.cmcc.online.smsapi.sdk.net.util.ServerUtil;
import cn.cmcc.online.smsapi.sdk.threadpool.SmartSmsThreadPoolManager;
import cn.cmcc.online.smsapi.sdk.util.DuoquUtils;
import cn.cmcc.online.smsapi.sdk.util.StringUtils;
import cn.cmcc.online.smsapi.sdk.util.XyUtil;
/* SDK-485 huangzhiqiang 20160622 start */
import java.util.Collections;
import java.util.Map;
/* SDK-485 huangzhiqiang 20160622 end */

/* SDK-616 hewengao/20160918 start */
/* SDK-616 hewengao/20160918 end */
/**
 * 归属地
 * 
 * @author Administrator
 * 
 */
public class IccidLocationUtil {

    private static final String TAG = "iccid";
//    public static final ExecutorService iccidPool = Executors.newFixedThreadPool(1);
//    public static final ExecutorService pubInfoPool = Executors.newFixedThreadPool(2);
    static long prevLoadIccidTime = 0;// 控制查询iccid归属地的频率。30s
    /* SDK-450 huangzhiqiang 20160624 start*/
    private static final HashMap<String, String[]> iccidAreaCodeMap = new HashMap<String, String[]>();
    /* SDK-450 huangzhiqiang 20160624 end*/
    private static boolean isLoadIccid = false;

    public static void changeIccidAreaCode(boolean reload) {
        if (reload || isLoadIccid == false) {
            isLoadIccid = true;
            iccidAreaCodeMap.clear();
            String iccid0 = DuoquUtils.getSdkDoAction().getIccidBySimIndex(0);
            String iccid1 = DuoquUtils.getSdkDoAction().getIccidBySimIndex(1);

            LogManager.d("IccidLocationUtil", "changeIccidAreaCode iccid0=",iccid0);
            LogManager.d("IccidLocationUtil", "changeIccidAreaCode iccid1=",iccid1);
            if (!StringUtils.isNull(iccid0)) {
                loadIccidInfoToCacheAndQueryNetIccidInfo(iccid0);
            }
            if (!StringUtils.isNull(iccid1)) {
                loadIccidInfoToCacheAndQueryNetIccidInfo(iccid1);
            }
        }
    }

    public static void loadIccidInfoToCacheAndQueryNetIccidInfo(String iccid) {
        IccidInfo iccidData = IccidInfoManager.queryIccidInfo(iccid, Constant.getContext());
        /* SDK-445 huangzhiqiang 20160519 start */
        /* SDK-450 huangzhiqiang 20160624 start*/
        if (iccidData != null) {
            putIccidAreaCodeToCache(iccid, iccidData.areaCode, iccidData.operator, iccidData.userAreacode,
                    iccidData.userOperator, iccidData.simIndex, iccidData.deft);
        } else {
            putIccidAreaCodeToCache(iccid, null, null, null, null, -1, 0);
        }
        /* SDK-450 huangzhiqiang 20160624 end*/
        updateIccidInfo(iccid, iccidData);
        /* SDK-445 huangzhiqiang 20160519 end */
    }

    /**
     * 缓存sim卡iccid对应区域编码、更新时间、运营商信息、用户设置的区域编码、用户设置的运营商
     * 
     * @param iccid
     * @param areaCode 区域编码
     * @param operator 运营商
     * @param userAreaCode 用户设置的区域编码
     * @param userOperator 用户设置的运营商
     * @param simIndex 卡位(-1:未知 0:卡1 1:卡2...)[用户手动设置归属地后才会有实际值]
     * @param isDefaultCard 是否默认卡(0:非默认卡 1:默认卡)
     */
    public static void putIccidAreaCodeToCache(String iccid, String areaCode, String operator, String userAreaCode,
            String userOperator, int simIndex, int isDefaultCard) {
        if (iccid == null) {
            return;
        }
        String[] codeArr = iccidAreaCodeMap.get(iccid);
        /* SDK-450 huangzhiqiang 20160624 start*/
        if (codeArr == null) {
            codeArr = new String[] { areaCode, String.valueOf(System.currentTimeMillis()),
                    getOperatorNum(iccid, operator), userAreaCode, getOperatorNum(null, userOperator),
                    String.valueOf(simIndex), String.valueOf(isDefaultCard) };
        } else {
            codeArr[0] = areaCode;
            codeArr[1] = String.valueOf(System.currentTimeMillis());
            codeArr[2] = getOperatorNum(iccid, operator);
            codeArr[3] = userAreaCode;
            codeArr[4] = getOperatorNum(null, userOperator);
            codeArr[5] = String.valueOf(simIndex);
            codeArr[6] = String.valueOf(isDefaultCard);
        }
        /* SDK-450 huangzhiqiang 20160624 end*/
        iccidAreaCodeMap.put(iccid, codeArr);
    }
    
    /**
     * 获取sim卡iccid对应的运营商编号
     * 
     * @param iccid
     * @param operator 移动|联通|电信|null
     * @return
     */
    public static String getOperatorNum(String iccid, String operator) {
        if (StringUtils.isNull(operator)) {
            return String.valueOf(getOperatorByICCID(iccid));
        }
        if ("移动".equals(operator)) {
            return "1";
        }
        if ("联通".equals(operator)) {
            return "2";
        }
        if ("电信".equals(operator)) {
            return "3";
        }
        return "-2"; // 未知
    }

    /**
     * 更新归属地信息
     * 
     * @param iccid
     * @param iccidData
     */
    private static void updateIccidInfo(String iccid, final IccidInfo iccidData){
        try {
            /* SDK-485 huangzhiqiang 20160622 start */
            if (StringUtils.isNull(iccid) || repeatedNetQueryIccid(iccid)) {
                return;
            }
            /* SDK-485 huangzhiqiang 20160622 end */
            
            if (iccidData == null) {
                queryIccid(null, iccid, null, true, true);
            } else {
                /*SDK-616 hewengao 20160912 start*/
                SmartSmsThreadPoolManager.iccidPool.execute(new Runnable() {
                /*SDK-616 hewengao 20160912 end*/
                    @Override
                    public void run() {
                        try {
                            loadIccidLocate(Constant.getContext(), iccidData, null, null, true, false);
                        } catch (Throwable e) {
                            LogManager.e(Constant.TAG, e.getMessage(), e);
                        }
                    }
                });
            }
        } catch (Throwable e) {
            LogManager.w(Constant.TAG, "IccidLocationUtil updateIccidInfo: ", e);
        }
    }

    /* SDK-485 huangzhiqiang 20160622 start */
    private static Map<String, Long> mIccidLastNetQueryTime = Collections.synchronizedMap(new HashMap<String, Long>());

    /**
     * 记录iccid联网查询时间
     * 
     * @param iccid
     * @param netQueryTime
     */
    private static void addIccidLastNetQueryTime(String iccid, long netQueryTime) {
        if (!StringUtils.isNull(iccid)) {
            mIccidLastNetQueryTime.put(iccid, netQueryTime);
        }
    }

    /**
     * 是否重复联网查询iccid信息
     * 
     * @param iccid
     * @return
     */
    private static boolean repeatedNetQueryIccid(String iccid) {
        if (StringUtils.isNull(iccid)) {
            return false;
        }
        Long lastQueryTime = mIccidLastNetQueryTime.get(iccid);
        if (lastQueryTime != null) {
            long iccidQueryCycle = DexUtil
                    .getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_REQUERY_ICCID_INFO_CYCLE, 30000);
            return (lastQueryTime + iccidQueryCycle) > System.currentTimeMillis();
        }
        return false;
    }
    /* SDK-485 huangzhiqiang 20160622 end */

    /**
     * 根据号码获所属运营商编号
     * 
     * @param num
     * @return 1:联通 2:移动 3:电信 -1:未知
     */
    public static int getOperatorByNum(String num) {
    	if(StringUtils.isNull(num))return-1;
        String mobile = "10086,1008611,1008601";
        if (mobile.indexOf(num) != -1) {
            return 1; // 移动
        }
        String unicom = "10010,10011";
        if (unicom.indexOf(num) != -1) {
            return 2; // 联通
        }
        String telecom = "10000,10001";
        if (telecom.indexOf(num) != -1) {
            return 3; // 电信
        }
        return -1; // 未知
    }

    /**
     * 根据ICCID获取支持的运营商编号
     * 
     * @param iccid
     * @return 1:移动 2:联通 3:电信 -2:未知
     */
    public static int getOperatorByICCID(String iccid) {
        if (iccid != null && iccid.length() > 6) {
            String v = iccid.substring(4, 6);
            if (v.equals("00") || v.equals("02") || v.equals("05")
                    || v.equals("08")) {
                return 1; // 移动
            } else if (v.equals("01")) {
                return 2; // 联通
            } else if (v.equals("03")) {
                return 3; // 电信
            }
        }
        return -2; // 未知
    }

    /**
     * 根据ICCID 获取支持的运营商名称缩写
     * @param iccid
     * @return CMCC：移动、CUTC：联通、CT：电信
     */
    public static String getOperatorNameByICCID(String iccid) {
        switch (getOperatorByICCID(iccid)) {
            case 1:
                return "CMCC";//移动
            case 2:
                return "CUTC";//联通
            case 3:
                return "CT";//电信
            default:
                return "CMCC";
        }
    }
/**
     * 加载iccid归属地
     * 
     * @param context
     * @param info
     *            iccid信息
     * @param sceneId
     *            情景
     * @param sms
     *            指纹
     * @param locateEnable
     *            是否启用了归属地功能
     * @return
     */
    static void loadIccidLocate(Context context, IccidInfo info,
            String sceneId, String sms, boolean locateEnable, boolean newThread) {

        if (info != null && !StringUtils.isNull(info.iccid)) {
            final long weekTime = DexUtil.getUpdateCycleByType(
                    OnlineUpdateCycleConfigInterface.TYPE_RELOAD_ICCID_LOCATE_CYCLE, 3600 * 24 * 7 * 8 * 1000L);// 默认值为8周

            if (info != null
                    && !StringUtils.isNull(info.provinces)
                    && info.provinces.equals("未知")
                    && (info.updateTime + weekTime < System.currentTimeMillis())) {
                locateEnable = true; // 未知,且时间超过
            } else if ((StringUtils.isNull(info.provinces) && info.updateTime == 0)
                    || (!StringUtils.isNull(info.provinces) && info.updateTime < System
                            .currentTimeMillis() - weekTime)) {
                // 归属地为null且更新时间为0 或者 归属地不为空且超过8周
                locateEnable = true;
            } else {
                locateEnable = false;
            }
            // int netType = XyUtil.checkNetWork(context);
            queryIccidInfoFromService(info, 1, locateEnable, context, newThread);
        }

    }

    /***
     * 查询归属地
     * 
     * @param iccidInfo
     * @param cmd
     * @param locateEnable
     * @param netType
     * @param ctx
     * @return
     */
    static IccidInfo queryIccidInfoFromService(final IccidInfo iccidInfo,
            final int cmd, boolean locateEnable, final Context ctx,
            boolean newThread) {

        if (locateEnable == false) {
            return iccidInfo;
        }
        String cnum = "";
        String iccid = null;
        String num = null;
        if (iccidInfo != null) {
            if (!StringUtils.isNull(iccidInfo.cnum)
                    && ("10000".equals(iccidInfo.num.trim())
                            || "10010".equals(iccidInfo.num.trim()) || "10086"
                                .equals(iccidInfo.num.trim()))) {
                cnum = iccidInfo.cnum;
            }
            iccid = iccidInfo.iccid;
            num = iccidInfo.num;
        }
        queryIccid(cnum, iccid, num, newThread, true);
        // QueryLocationRequest(cnum, iccidInfo.iccid, iccidInfo.num);
        return null;
    }

    /**
     * 开启查询iccid归属地
     * 
     * @param paramsMap
     */
    public static void startQueryIccidLocation(
            HashMap<String, String> paramsMap, boolean newThread) {
        if (paramsMap != null) {
            String simIccid = paramsMap.get("simIccid");
            String receiveNum = paramsMap.get("receiveNum");
            String centerNum = paramsMap.get("centerNum");
            String sceneId = paramsMap.get("sceneId");
            String sms = paramsMap.get("sms");
            String smsLocate = paramsMap.get("smsLocate");

            IccidInfo info = null;
            if (simIccid == null) {
                // 获取默认的iccid
                info = IccidInfoManager.queryDeftIccidInfo(Constant
                        .getContext());
            } else {// 搜索已存记录
                info = IccidInfoManager.queryIccidInfo(simIccid,
                        Constant.getContext());
            }
            if (info == null) {
                info = new IccidInfo();
                info.cnum = centerNum;
                info.iccid = simIccid;
                info.num = receiveNum;
            } else {
                if (centerNum != null && centerNum.length() > 0
                        && info.cnum == null) {
                    info.cnum = centerNum;
                }
                if (receiveNum != null && receiveNum.length() > 0
                        && info.num == null) {
                    info.num = receiveNum;
                }
            }

            IccidInfoManager.updateIccidCnum(info.iccid, centerNum, receiveNum,
                    Constant.getContext());
            loadIccidLocate(Constant.getContext(), info, sceneId, sms,
                    SysParamEntityManager.getBooleanParam(
                            Constant.getContext(), Constant.SMSLOCATEENABLE),
                    newThread);
        }
    }

    // 获取手机的iccid
    public static String getICCID(Context context) {
        /*SDK-600 hewengao/20160825 start*/
        try{
            IccidInfo iccidInfo = IccidInfoManager.queryDeftIccidInfo(context);
            if (iccidInfo != null) {
                if (!StringUtils.isNull(iccidInfo.iccid)) {
                    return iccidInfo.iccid;
                }
            }
            TelephonyManager manager = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            if (!StringUtils.isNull(manager.getSimSerialNumber())) {
                return manager.getSimSerialNumber();
            }
        }catch(Throwable e){
            LogManager.w("XIAOYUAN", "IccidLocationUtil.getICCID: ", e);
        }
        /*SDK-600 hewengao/20160825 end*/
        return "";
    }

    /* SDK-485 huangzhiqiang 20160622 start */
    public static String getAreaCodeByCnumOrIccid(String cnum, int simIndex, String iccid, String num) {
        try {
            queryIccidAreaCodeInfoIfNeed(iccid);

            /* 尝试获取用户设置的归属地 */
            String userAreaCode = getUserAreaCode(iccid, simIndex);
            if (!StringUtils.isNull(userAreaCode)) {
                LogManager.d("IccidLocationUtil"," getAreaCodeByCnumOrIccid优先返回用户设置的区域编码 areaCode=", userAreaCode);
                return userAreaCode;
            }

            /* 尝试通过短信中心号码获取归属地 */
            CenterNumLocationInfo centerNumLocationInfo = queryCenterNumLocationInfo(cnum);
            updateAreaCodeByCenterNumIfNeed(cnum, centerNumLocationInfo, iccid, num, true, true);
            if (centerNumLocationInfo != null && !StringUtils.isNull(centerNumLocationInfo.areaCode)) {
                LogManager.d("IccidLocationUtil","getAreaCodeByCnumOrIccid 返回短信中心的区域编码 areaCode=", centerNumLocationInfo.areaCode);
                return centerNumLocationInfo.areaCode;
            }

            changeIccidAreaCode(false); // 跨进程没有初始化SDK时需要执行该方法加载iccid信息到缓存 

            /* 外部指定了iccid则只查询该iccid的区域数据 */
            if (!StringUtils.isNull(iccid)) {
                String areaCode = getAreaCodeFromCache(iccid);
                if (!StringUtils.isNull(areaCode)) {
                    return areaCode;
                }
            } else {
                /* SDK-450 huangzhiqiang 20160624 start*/
                /* 外部没有指定iccid，遍历所有iccid归属地数据，找到匹配数据的区域 */
                // 号码所属运营商
                String numOperator = String.valueOf(getOperatorByNum(num));
                // 非运营商号码
                if ("-1".equals(numOperator)) {
                    // 所有sim卡为同一归属地时直接返回该归属地
                    String areaCode = getAreaCodeIfAllCardIsSameArea();
                    if (!StringUtils.isNull(areaCode)) {
                        LogManager.d("IccidLocationUtil", "所有sim卡为同一区域 areaCode=", areaCode);
                        return areaCode;
                    }

                    // 尝试获取默认卡的归属地
                    areaCode = getAreaCodeByDefaultCard();
                    if (!StringUtils.isNull(areaCode)) {
                        LogManager.d("IccidLocationUtil", "getAreaCodeByCnumOrIccid 返回默认卡的区域编码 areaCode=",areaCode);
                        return areaCode;
                    }
                } else {
                    // 运营商号码
                    // 尝试通过运营商获取归属地
                    String areaCode = getAreaCodeByNumOperator(numOperator);
                    if (!StringUtils.isNull(areaCode)) {
                        LogManager.d("IccidLocationUtil getAreaCodeByCnumOrIccid", "返回运营商匹配通过的区域编码 areaCode=",areaCode);
                        return areaCode;
                    }
                }
                /* SDK-450 huangzhiqiang 20160624 end*/
            }
        } catch (Throwable e) {
            LogManager.w(Constant.TAG, "getAreaCodeByCnumOrIccid: ", e);
        }
        LogManager.d("IccidLocationUtil getAreaCodeByCnumOrIccid", "没有任何匹配区域或出现异常，返回CN");
        return "CN";
    }

    /**
     * 没有iccid区域缓存数据时，从数据库读取iccid数据并放入缓存，本地不存在iccid数据时联网查询iccid数据，
     * 相同iccid一小时只联网查询一次
     *
     * @param iccid
     */
    private static void queryIccidAreaCodeInfoIfNeed(String iccid) {
        if (StringUtils.isNull(iccid)) {
            return;
        }
        boolean noAreaCodeInfo = (iccidAreaCodeMap.get(iccid) == null
                || StringUtils.isNull(iccidAreaCodeMap.get(iccid)[0]));
        if (noAreaCodeInfo) {
            loadIccidInfoToCacheAndQueryNetIccidInfo(iccid);
        }
    }

    /* SDK-450 huangzhiqiang 20160624 start*/
    /**
     * 根据sim卡iccid或卡位获取用户设置的区域编码
     * 
     * @param iccid
     * @param simIndex
     * @return
     */
    public static String getUserAreaCode(String iccid, int simIndex) {
        String userAreaCode = getIccidAreaCodeMapValueByIndex(iccid, 3);
        if (!StringUtils.isNull(userAreaCode)) {
            LogManager.d("IccidLocationUtil getUserAreaCode", "通过iccid获取到用户设置的区域编码 areaCode=", userAreaCode);
            return userAreaCode;
        }
        if (simIndex >= 0) {
            userAreaCode = getUserAreaCodeBySimIndex(simIndex);
            LogManager.d("IccidLocationUtil getUserAreaCode", "通过卡位获取用户设置的区域编码 areaCode=" , userAreaCode);
            return userAreaCode;
        }
        return null;
    }

    private static String getUserAreaCodeBySimIndex(int simIndex) {
        Set<Entry<String, String[]>> setEntery = iccidAreaCodeMap.entrySet();
        String strSimIndex = String.valueOf(simIndex);
        for (Entry<String, String[]> entry : setEntery) {
            String[] iccidInfoArr = entry.getValue();
            String userAreaCode = iccidInfoArr[3];
            String index = iccidInfoArr[5];
            if (strSimIndex.equals(index)) {
                return userAreaCode;
            }
        }
        return null;
    }
    /* SDK-450 huangzhiqiang 20160624 end*/

    private static CenterNumLocationInfo queryCenterNumLocationInfo(String centerNum) {
        String cNum = StringUtils.getPhoneNumberNo86(centerNum);
        if (StringUtils.isNull(cNum)) {
            return null;
        }
        cNum = StringUtils.getSubString(cNum);
        /* SDK-485 huangzhiqiang 20160622 start */
        /* SDK-450 huangzhiqiang 20160624 start*/
        CenterNumLocationInfo centerNumLocationInfo = CNumLocationInfoManager.getCenterNumberLoactionInfoCache(cNum);
        if (centerNumLocationInfo != null) {
            return centerNumLocationInfo;
        }
        centerNumLocationInfo = CNumLocationInfoManager.queryCenterNumLocationInfo(cNum);
        if (centerNumLocationInfo != null) {
            CNumLocationInfoManager.addCenterNumberLoactionInfoCache(cNum, centerNumLocationInfo);
        }
        return centerNumLocationInfo;
        /* SDK-450 huangzhiqiang 20160624 end*/
        /* SDK-485 huangzhiqiang 20160622 end */
    }

    /**
     * 无短信中心号码对应数据或短信中心号码已过期，联网查询短信中心号的归属地信息
     * 
     * @param centerNum 短信中心号
     * @param centerNumLocationInfo 短信中心号信息，非必填
     * @param iccid 非必填
     * @param num 非必填
     * @param newThread 在新线程执行联网查询
     * @param checkEnhance 检查增强服务开关是否开启 true:检查 false:不检查
     */
    private static void updateAreaCodeByCenterNumIfNeed(String centerNum, CenterNumLocationInfo centerNumLocationInfo,
            String iccid, String num, boolean newThread, boolean checkEnhance) {
        if (StringUtils.isNull(centerNum)) {
            return;
        }

        // 有短信中心数据且未过3个月更新周期，不需要联网查询
        /* RM-1404 2017-03-28 mobaohua start */
        //需求改为30天
        if (centerNumLocationInfo != null && centerNumLocationInfo.checkTime > System.currentTimeMillis() - DexUtil
                .getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_CENTER_NUM_LOCATION_INFO_CHECK_CYCLE,
                        Constant.month * 1)) {
            return;
        }
        /* RM-1404 2017-03-28 mobaohua end */

        // 联网查询短信中心的归属地信息
        queryIccid(centerNum, iccid, num, newThread, checkEnhance);
    }

    private static String getAreaCodeFromCache(String iccid) {
        if (StringUtils.isNull(iccid)) {
            return null;
        }
        String[] iccidInfoArr = iccidAreaCodeMap.get(iccid);
        if (iccidInfoArr == null) {
            return null;
        }
        String areaCode = iccidInfoArr[0];
        return StringUtils.isNull(areaCode) ? null : areaCode;
    }

    private static String getAreaCodeByNumOperator(String numOperator) {
        if (iccidAreaCodeMap.isEmpty() || StringUtils.isNull(numOperator)) {
            return null;
        }
        try {
            String areaCode = null;
            int operatorMatchedCount = 0;
            int areaCodeSameCount = 0;

            Set<Entry<String, String[]>> setEntery = iccidAreaCodeMap.entrySet();
            for (Entry<String, String[]> entry : setEntery) {
                String[] iccidInfoArr = entry.getValue();
                String simCardAreaCode = iccidInfoArr[0];
                String simCardOperator = iccidInfoArr[2];
                String userAreaCode = iccidInfoArr[3];
                String userOperator = iccidInfoArr[4];

                // 用户设置的运营商信息与当前号码运营商匹配
                if (operatorMatchedAndAreaCodeNotNull(numOperator, userOperator, userAreaCode)) {
                    // 当前的用户设置区域与上一个区域相同时，区域匹配++
                    if (userAreaCode.equals(areaCode)) {
                        areaCodeSameCount++;
                    }
                    operatorMatchedCount++;
                    areaCode = userAreaCode;
                    // 用户没有设置区域且sim卡的运营商信息与当前号码运营商匹配
                } else if (StringUtils.isNull(userAreaCode)
                        && operatorMatchedAndAreaCodeNotNull(numOperator, simCardOperator, simCardAreaCode)) {
                    // 当前的sim卡区域与上一个区域相同时，区域匹配++
                    if (simCardAreaCode.equals(areaCode)) {
                        areaCodeSameCount++;
                    }
                    operatorMatchedCount++;
                    areaCode = simCardAreaCode;
                }
            }

            // 符合以下两个条件的才返回区域
            // 1、所有sim卡中只有其中一张卡的运营商和公众号的运营商是匹配的，返回该张卡的区域
            // 2、所有sim卡的运营商都和公众号的运营商匹配，并且所有卡都是同一省份的，返回该省份
            if (operatorMatchedCount == 1 || (operatorMatchedCount == iccidAreaCodeMap.size()
                    && areaCodeSameCount + 1 == iccidAreaCodeMap.size())) {
                return areaCode;
            }
        } catch (Throwable e) {
            LogManager.w(Constant.TAG, "IccidLocationUtil getAreaCodeByNumOperator: ", e);
        }
        return null;
    }

    private static boolean operatorMatchedAndAreaCodeNotNull(String numOperator, String operator, String areaCode) {
        return !StringUtils.isNull(operator) && operator.equals(numOperator) && !StringUtils.isNull(areaCode);
    }
    /* SDK-485 huangzhiqiang 20160622 end */

    /* SDK-450 huangzhiqiang 20160624 start*/
    private static String getAreaCodeIfAllCardIsSameArea() {
        Set<Entry<String, String[]>> setEntery = iccidAreaCodeMap.entrySet();
        String areaCode = null;
        for (Entry<String, String[]> entry : setEntery) {
            String[] iccidInfoArr = entry.getValue();
            String simCardAreaCode = iccidInfoArr[0];
            String userAreaCode = iccidInfoArr[3];
            if (!StringUtils.isNull(userAreaCode)) {
                // 与上一张卡的区域不同，直接返回null
                if (areaCode != null && !areaCode.equals(userAreaCode)) {
                    return null;
                }
                areaCode = userAreaCode;
            } else if (!StringUtils.isNull(simCardAreaCode)) {
                // 与上一张卡的区域不同，直接返回null
                if (areaCode != null && !areaCode.equals(simCardAreaCode)) {
                    return null;
                }
                areaCode = simCardAreaCode;
            } else {
                // 任何一张卡同时没有网络查到的区域和用户手动设置的区域时直接返回null
                return null;
            }
        }
        // 所有sim卡的区域都相同，返回该区域
        return areaCode;
    }

    public static String getAreaCodeByDefaultCard() {
        Set<Entry<String, String[]>> setEntery = iccidAreaCodeMap.entrySet();
        for (Entry<String, String[]> entry : setEntery) {
            String[] iccidInfoArr = entry.getValue();
            String simCardAreaCode = iccidInfoArr[0];
            String userAreaCode = iccidInfoArr[3];
            String isDefaultCard = iccidInfoArr[6];
            if ("1".equals(isDefaultCard)) {
                return StringUtils.isNull(userAreaCode) ? simCardAreaCode : userAreaCode;
            }
        }
        return null;
    }
    /* SDK-450 huangzhiqiang 20160624 end*/

    /**
     * 获取省份
     * 
     * @return
     */
    public static String getProvince() {
        IccidInfo iccidInfo;
        iccidInfo = IccidInfoManager.queryDeftIccidInfo(Constant.getContext());
        if (iccidInfo != null) {
            return iccidInfo.provinces;
        }
        return "";
    }
    
    /**
     * 获取areaCoce
     * 
     * @return
     */
    public static String getAreaCoce() {
        IccidInfo iccidInfo;
        iccidInfo = IccidInfoManager.queryDeftIccidInfo(Constant.getContext());
        if (iccidInfo != null) {
            return iccidInfo.areaCode;
        }
        return "";
    }


    /**
     * 查询归属地请求 此方法为内部是同步的，外部注意需要使用异步
     * 
     * @param cNum
     * @param iccid
     * @param newThread
     */
    private static void queryLocationRequest(final String cNum,
            final String iccid, String num, boolean newThread) {
        try {
            NetUtil.requestTokenIfNeed(iccid);
            XyCallBack callback = new XyCallBack() {
                @Override
                public void execute(Object... obj) {
                    // TODO Auto-generated method stub
                    if (obj != null) {
                        String resutCode = obj[0].toString();
                        LogManager.d("QueryLocationRequest", "resutCode=", resutCode);
                        if (resutCode.equals("0") && obj.length == 2) {
                            String response = obj[1].toString();
                            LogManager.d("IccidLocationUtil QueryLocationRequestresponse=",response);
                            CenterNumLocationInfo info = ServerUtil
                                    .parseQueryLocationRespose(response);
                            if (info.id == ServerUtil.success) {
                                info.cNum = StringUtils.getSubString(cNum);
                                info.checkTime = System.currentTimeMillis();
                                if (!StringUtils.isNull(cNum)) {// 短信中心不为空
                                    /* SDK-450 huangzhiqiang 20160624 start */
                                    if (CNumLocationInfoManager.saveCNumLocationInfo(info)) {
                                        CNumLocationInfoManager.addCenterNumberLoactionInfoCache(info.cNum, info);
                                    }
                                    /* SDK-450 huangzhiqiang 20160624 end */
                                } else if (!StringUtils.isNull(iccid)) {// iccid
                                    IccidInfoManager.insertIccid(iccid, true,
                                            info.province, info.areaCode,
                                            info.city, info.operator,
                                            Constant.getContext());
                                }
                            } else if (info.id == ServerUtil.tokenOut) {
                                NetUtil.QueryTokenRequest(iccid);
                            }
                        }
                    }
                }
            };
            LogManager.d("IccidLocationUtil QueryLocationRequest query","iccid=" ,iccid);

            /* SDK-504 huangzhiqiang 20160623 start */
            String dataString = ServerUtil.QueryLocationRequest(cNum, iccid, num);
            if (!StringUtils.isNull(dataString)) {
                NetUtil.executeAllNetHttpRequest(dataString, "990005", callback, newThread, false,
                        NetUtil.REQ_QUERY_LOCATION, false);
            }
            /* SDK-504 huangzhiqiang 20160623 end */
        } catch (Throwable e) {
            LogManager.w(Constant.TAG, "queryLocationRequest: ", e);
        }
    }

   /* *//***
     * 检测增加服务开关
     * 
     * @param checkEnhance
     *            true 需要检测增强服务开关，false 不需要检测增加开关。
     * @return
     *//*
    public static boolean isEnhance(boolean checkEnhance) {
        if (checkEnhance) {
            return SysParamEntityManager.getBooleanParam(Constant.getContext(),
                    Constant.SMARTSMS_ENHANCE, true);
        }
        return true;
    }
*/
    /**
     * 查询iccid
     * 
     * @param cNum
     *            短信中心号码
     * @param iccid
     *            iccid
     * @param num
     *            号码
     * @param newThread
     *            true 新开线程 false 不需要新开线程
     * @param checkEnhance
     *            true 需要检测增强服务开关，false 不需要检测增加开关（目前没有使用该参数，永远是检测增强服务器开关）
     */
    public static void queryIccid(String cNum, final String iccid, final String num, boolean newThread,
            boolean checkEnhance) {
        try {
            if (!NetUtil.isEnhance()) {
                LogManager.d("duoqu_xiaoyuan", "queryIccid need Constant.SMARTSMS_ENHANCE is TRUE.. but is false");
                return;
            }

            addIccidLastNetQueryTime(iccid, System.currentTimeMillis());

            /*SDK-688 zhaojiangwei 20161129 start */
            cNum = StringUtils.getPhoneNumberNo86(cNum);
            /*SDK-688 zhaojiangwei 20161129 end */
            if (!newThread) {
                queryLocationRequest(cNum, iccid, num, false);
                return;
            }
            final String tempCNum = cNum;
            /*SDK-616 hewengao 20160912 start*/
            SmartSmsThreadPoolManager.iccidPool.execute(new Runnable() {
            /*SDK-616 hewengao 20160912 end*/
                @Override
                public void run() {
                    try {                    	
                        queryLocationRequest(tempCNum, iccid, num, false);
                    } catch (Throwable e) {
                        LogManager.w(Constant.TAG, e.getMessage(), e);
                    }
                }
            });
        } catch (Throwable e) {
            LogManager.w(Constant.TAG, "IccidLocationUtil queryIccid: ", e);
        }
    }
    
    /**
     * 获取所有缓存的iccid对应区域信息
     * 
     * @return iccid对应信息数组【index0:所属区域编码 index1:数据更新时间
     *            index2:所属运营商编号 index3:用户设置的区域编码 index4:用户设置的运营商编号】其中运营商编号为(1:移动
     *            2:联通 3:电信 -2:未知)
     */
    public static HashMap<String, String[]> getIccidAreaCodeMap() {
        return iccidAreaCodeMap;
    }
    
    /**
     * 获取缓存的iccid对应区域信息
     * 
     * @param iccid
     * @return
     */
    public static String[] getIccidInfoArr(String iccid) {
        return iccidAreaCodeMap.get(iccid);
    }
    
    /**
     * 获取iccid信息中用户设置的运营商编号
     * 
     * @param iccidInfoArr
     * @return
     */
    public static int getUserOperatorNum(String[] iccidInfoArr){
        int userOperatorNum = -2;
        if (iccidInfoArr.length > 4 && !StringUtils.isNull(iccidInfoArr[4])) {
            try {
                userOperatorNum = Integer.parseInt(iccidInfoArr[4]);
            } catch (Throwable ex) {
            }
        }
        return userOperatorNum;
    }
    
    /**
     * 根据索引获取iccid缓存信息值
     * 
     * @param iccid
     * @param index 【index0:所属区域编码 index1:数据更新时间
     *            index2:所属运营商编号 index3:用户设置的区域编码 index4:用户设置的运营商编号】其中运营商编号为(1:移动
     *            2:联通 3:电信 -2:未知)
     * @return
     */
    public static String getIccidAreaCodeMapValueByIndex(String iccid, int index) {
        if (StringUtils.isNull(iccid) || iccidAreaCodeMap == null || iccidAreaCodeMap.isEmpty()) {
            return null;
        }
        String[] iccidInfoArr = iccidAreaCodeMap.get(iccid);
        if (iccidInfoArr != null && iccidInfoArr.length > index) {
            return iccidInfoArr[index];
        }
        return null;
    }
    
    public static boolean queryAreaCode(boolean newThread) {
		
		try {
			IccidInfo iccidInfo = IccidInfoManager.queryDeftIccidInfo(Constant.getContext());

			if (iccidInfo == null) {
				HashMap<String, String> paramsMap = new HashMap<String, String>();
				paramsMap.put("simIccid", XyUtil.getIccid());
				IccidLocationUtil.startQueryIccidLocation(paramsMap, newThread);
				return false;
			}
		} catch (Exception e) {
			// TODO: handle exception
			 LogManager.e(Constant.TAG, "queryAreaCode: ", e);
		}
		// 通过中心号码或者iccid查询区域
		return true;
	}

    /* SDK-485 huangzhiqiang 20160622 start */
    /**
     * 更新归属地信息缓存，会根据iccid或simIndex获取归属地数据，当iccid为空时将使用simIndex作为缓存数据的key
     * 
     * @param iccid
     * @param simIndex
     */
    public static void updateIccidCache(String iccid, int simIndex) {
        IccidInfo iccidData = IccidInfoManager.queryIccidInfo(iccid, simIndex);
        if (iccidData != null) {
            String key = iccid;
            if (StringUtils.isNull(key)) {
                key = String.valueOf(simIndex);
            }
            /* SDK-450 huangzhiqiang 20160624 start*/
            // 添加或更新数据缓存
            putIccidAreaCodeToCache(key, iccidData.areaCode, iccidData.operator, iccidData.userAreacode,
                    iccidData.userOperator, iccidData.simIndex, iccidData.deft);
            /* SDK-450 huangzhiqiang 20160624 end*/
        }
    }
    /* SDK-485 huangzhiqiang 20160622 end */
}
